<?php

use Illuminate\Database\Eloquent\Model;

class goodscommentModel extends Model
{
    protected $table = 'goods_comment';
    protected $primaryKey = 'id';

    public static $typeAll = [
        'all'      => ['code' => 'all', 'name' => '全部'],
        'images'   => ['code' => 'images', 'name' => '有图'],
        'good'     => ['code' => 'good', 'name' => '好评'],
        'moderate' => ['code' => 'moderate', 'name' => '中评'],
        'bad'      => ['code' => 'bad', 'name' => '差评'],
    ];

    public function scopeImages($query)
    {
        return $query->whereNotNull('images')->where('images', '<>', '');
    }

    public function scopeGood($query)
    {
        return $query->where('level', 'in', [5, 4]);
    }

    public function scopeModerate($query)
    {
        return $query->where('level', 'in', [3, 2]);
    }

    public function scopeBad($query)
    {
        return $query->where('level', 1);
    }

    protected function serializeDate($date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function member()
    {
        return $this->belongsTo(memberModel::class, 'member_id', 'id');
    }

    public function goods()
    {
        return $this->belongsTo(goodsModel::class, 'goods_id', 'id');
    }

    public static function getList($params)
    {
        $goods_id = $params['goods_id'] ?? 0;
        $type     = $params['type'] ?? 'all';
        $page     = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;

        $query = (new self)->with(['member' => function ($query) {
            $query->select(['id', 'nickname', 'avatar']);
        }])->where('goods_id', $goods_id)
            ->where('parent_id', 0)
            ->where('status', 'show');

        if ($type != 'all' && isset(self::$typeAll[$type])) {
            $query->{$type}();
        }

        $total = $query->count();
        $data  = $query
            ->orderBy('id', 'desc')
            ->offset(($page - 1) * $per_page)
            ->limit($per_page)
            ->get()
            ->toArray();
        foreach ($data as $k => $v) {
            $time = $v['created_at'];
            if (empty($time)) {
                $time = orderModel::where('id', $v['order_id'])->value('updated_at');
            }
            $data[$k]['images'] = array_filter(explode(',', $v['images']));
            $data[$k]['createtime'] = strtotime($time);
            if (!empty($v['user'])) {
                $data[$k]['user']['nickname'] = $v['user']['nickname_hide'];
                unset($data[$k]['user']['nickname_hide']);
            }
            $data[$k]['sub_comment'] = self::query()->where('parent_id', $v['id'])->where('status', 'show')->get()->toArray();
        }

        return [
            'current_page' => $page,
            'last_page'    => ceil($total / $per_page),
            'per_page'     => $per_page,
            'total'        => $total,
            'data'         => $data,
        ];
    }
}

